<template>
    <router-link custom v-slot="{ navigate }" :to="{name:'envs'}">
        <span ref="entrance" @click="navigate" class="circle f14 gray-1" :class="{active:active}" :style="position" v-show="showEnvs && $route.name!='envs'">{{env}}</span>
    </router-link>
</template>
<script>
import { getCurrentInstance, onMounted, reactive, ref, watch, nextTick } from 'vue'
import {throttle} from '@/utils'
export default {
    setup(){
        const self = getCurrentInstance()
        const active = ref(false)
        const env = ref(localStorage.getItem('env'))
        const showEnvs = ref(env.value?true:false)
        const position = reactive({left:null, top:null})
        const entrance = ref(null)
        onMounted(()=>{
            showEnvs.value && initDrag()
        })

        watch(showEnvs, _new=>{
            updateEnv()
            nextTick(()=>{
                _new && initDrag()
            })
        })

        function initDrag(){ //初始化拖动
            const $el = $(entrance.value)
            $el.on('touchmove', throttle((args)=>{
                let [e] = args
                if (e.targetTouches.length == 1) {
                    let touch = e.targetTouches[0]
                    let _x = touch.pageX
                    _x = _x<$el.width()/2?$el.width()/2:_x
                    _x = _x>($(window).width()-$el.width()/2)?$(window).width()-$el.width()/2:_x
                    let _y = touch.pageY
                    _y = _y<$el.height()/2?$el.height()/2:_y
                    _y = _y>($(window).height()-$el.height()/2)?$(window).height()-$el.height()/2:_y
                    position.left = _x+'px'
                    position.top = _y+'px'
                }
            },20)).on('touchstart', e=>{
                active.value = true
            }).on('touchend', e=>{
                active.value = false
            })
        }

        function updateEnv(){ //更新当前显示环境
            env.value = localStorage.getItem('env')
        }

        return {
            env,
            showEnvs,
            position,
            active,
            entrance
        }
    }
}
</script>
<style lang="less" scoped>
.circle {
    position: fixed;
    z-index: 1;
    left: 80%;
    top: 80%;
    border-radius: 100%;
    height: 40px;
    width: 40px;
    margin-left: -20px;
    margin-top: -20px;
    background-color: rgba(255,255,255, .5);
    line-height: 40px;
    text-align: center;
    color: rgba(0,0,0, .3);
    opacity: .8;
    border: 1px solid rgba(0,0,0, .3);
    &.active {
        background-color: rgba(255,255,255, .7);
    }
}
</style>